import socket,struct
import pickle
from dam import *
from datetime import datetime    
from helpFunc import *
def getText(num,file=''):
    import json    
    f = open('con_controlPort.txt')
    s = f.read()
    f.close()
    m = json.loads(s)
    port = m['con_controlPort3']        
    s = socket.socket()
    add = ('127.0.0.1',port)
    s.connect(add)
    ss = struct.pack('H',num)
    s.sendall(ss)
    st = b''
    damClass = dam()
    while True:
        try:
            r = s.recv(65536)
            if not r:
                break
            st += r
        except:
            break
    s.close()    
    m = {}
    if st:
        m = pickle.loads(st)
    st2 = st    
    co = 0
    pp = ''    
    
    for one in m:
        co += 1
        s,t,st = one
        now = datetime.fromtimestamp(t)
        if s==0:
            if con_keyLen%3:
                st = b'\x00'*(3-con_keyLen%3)+st
            pp += '%s <-- %s %s\n'%(co,now.strftime("%H:%M:%S.%f")[:-3],damClass.b2chi(st))
        else:
            pp += '%s --> %s %s\n'%(co,now.strftime("%H:%M:%S.%f")[:-3],damClass.b2chi(st))
    if file:
        f = open(file,'w')
        f.write(pp)
        f.close()
    print (len(m),len(pp))
    return len(m),pp
if __name__=='__main__':    
    getText( 0,'a.txt')
#s = socket.socket()
#add = ('127.0.0.1',con_controlPort)
#s.connect(add)
#l = 470
#ss = struct.pack('H',l)
#s.sendall(ss)
#s.close()
#s = socket.socket()
#add = ('127.0.0.1',con_controlPort2)
#s.connect(add)
#l = 1200*1024
#ss = struct.pack('i',l)
#s.sendall(ss)
#s.close()
